<template>
    <div>
        <!-- 三级分类全局组件 -->
        <category :show="show"></category>
        <div v-show="show==0">
            <el-card shadow="hover" :body-style="{ padding: '20px' }" style="margin: 10px 0;">
                <el-button type="primary" size="default" :icon="Plus" @click="addAttr" :disabled="!categoryStore.c3Id">
                    添加属性</el-button>

                <el-table border style="margin:10px 0" :data="attrList">
                    <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
                    <el-table-column label="属性名称" width="160" prop="attrName" show-overflow-tooltip></el-table-column>
                    <el-table-column label="属性值列表">
                        <template #="{row,$index}">
                            <el-tag class="ml-2" type="success" v-for="(item,index) in row.attrValueList" :key="item.id"
                                style="margin-right: 10px;">{{item.valueName}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="160">
                        <template #="{row,$index}">
                            <el-button type="warning" size="small" :icon="Edit" @click="updateAttr(row)"></el-button>
                            <el-button type="danger" size="small" :icon="Delete" @click="removeAttr(row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>
        <!--添加属性 -->
        <div v-show="show != 0">
            <el-card shadow="hover" :body-style="{ padding: '20px' }" style="margin: 10px 0;">
                <!-- 点击添加属性 显示 -->
                <el-form style="width:20%" v-if="show">
                    <!-- 添加属性名 -->
                    <el-form-item label="属性名">
                        <el-input type="text" placeholder="请输入属性名称" v-model="attr.attrName"></el-input>
                    </el-form-item>
                </el-form>

                <el-button type="primary" size="default" :icon="Plus" @click="addAttrValue"
                    :disabled="attr.attrName==''">添加属性值</el-button>
                <el-button size="default" v-if="show" @click="cancel">取消</el-button>

                <el-table border style="margin:10px 0" :data="attr.attrValueList">
                    <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
                    <el-table-column label="属性值">
                        <template #="{row,$index}">
                            <el-input :ref="(vc)=>(inputArr[$index]=vc)" v-if="row.flag" placeholder="请输入属性值名称"
                                type="text" size="small" v-model="row.valueName" @blur="toLook(row,$index)"></el-input>
                            <div v-else @click="toEdit(row,$index)">{{row.valueName}}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #="{row,$index}">
                            <el-button type="danger" size="small" :icon="Delete"
                                @click="attr.attrValueList.splice($index,1)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" size="default" @click="saveHandler"
                    :disabled="attr.attrValueList.length > 0 ? false : true">
                    保存</el-button>
                <el-button size="default" @click="cancel">取消</el-button>
            </el-card>
        </div>
    </div>

</template>

<script setup lang="ts">
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus
} from '@element-plus/icons-vue'
import type { attrResponseData, attrData, attrValue, } from '@/api/product/attr/model/attr'
// 引入仓库
import useCategoryStore from '@/stores/category';
import { reqAddAttr, reqAttrList,reqDeleteAttr } from '@/api/product/attr/attr'
import { ref, watch, reactive, nextTick, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
// 引入lodash中的深拷贝
import cloneDeep from 'lodash/cloneDeep'
let categoryStore = useCategoryStore()
// 控制添加属性的显示与隐藏
let show = ref<number>(0)
// 存储平台属性
let attrList = ref<attrResponseData>([])
//定义数组ref类型数据，将来存储el-input组件的实例
let inputArr = ref<any>([]);


// 定义一个平台属性对象
let attr = reactive<attrData>({
    attrName: '',
    attrValueList: [],
    categoryId: 1,
    categoryLevel: 3,
    id:''
})
// 监听三级分类id的变化 发生变化就发请求
watch(
    () => categoryStore.c3Id,
    () => {
        attrList.value = []
        if (categoryStore.c3Id == '') return
        getAttrList()
    }
)

// 获取平台属性的请求
const getAttrList = async () => {
    let result = await reqAttrList(categoryStore.c1Id, categoryStore.c2Id, categoryStore.c3Id)
    console.log(result);
    // 存储平台属性
    attrList.value = result
}
// 点击添加属性按钮
const addAttr = () => {
    show.value = 1
    // 清空数据
    Object.assign(attr, {
        attrName: '',
        attrValueList: [],
        categoryId: categoryStore.c3Id,
        categoryLevel: 3,
        id:''
    })
}

// 点击保存按钮
const saveHandler = async () => {
    attr.attrValueList = attr.attrValueList.map((item) => {
        return {
            valueName: item.valueName
        }
    })
    try {
        let result = await reqAddAttr(attr)
        console.log(result);
        show.value = 0
        ElMessage({
            type: 'success',
            message:attr.id ? "修改成功" : "添加成功",
        })
        getAttrList()
    } catch (error) {
        ElMessage({
            type: 'error',
            message:attr.id ? "修改失败" : "添加失败",
        })
    }
}

//点击取消按钮
const cancel = () => {
    show.value = 0
}

// 点击添加属性值按钮
const addAttrValue = () => {
    attr.attrValueList.push({
        valueName: '',
        // 给每一个属性添加一个标记 用来切换修改、查看模式
        flag: true
    })
    //获取el-input组件实例,数组最后这个元素
    nextTick(() => {
        inputArr.value[attr.attrValueList.length - 1].focus();
    })
}

//input失却焦点变为查看模式
const toLook = (row: attrValue, $index: number) => {
    // 若属性值为空
    if (row.valueName.trim() == '') {
        ElMessage({
            type: 'warning',
            message: '属性值不能为空'
        })
        // 属性值数组把当前为空的属性值对象删除
        attr.attrValueList.splice($index, 1)
        return
    }
    // 属性值重名
    let repeat = attr.attrValueList.find((item) => {
        // 先把数组当中的自身扣除
        if (row != item) {
            return row.valueName === item.valueName
        }
    })
    // 如果出现重复
    if (repeat) {
        ElMessage({
            type: 'warning',
            message: `${repeat.valueName}重复？`
        })
        //属性值数组把当前重复的属性值对象删除
        attr.attrValueList.splice($index, 1)
        return
    }
    row.flag = false;
};
//div点击切换为编辑模式
const toEdit = (row: attrValue, $index: number) => {
    row.flag = true;

    // 点击div切换显示el-input，需要聚焦
    nextTick(() => {
        inputArr.value[$index].focus()
    })
};

// 点击修改按钮
const updateAttr =(row:attrData)=>{
    show.value = 1
    // 获取数据
    Object.assign(attr,cloneDeep(row))
    // console.log(cloneDeep);  
}

// 点击删除按钮
const removeAttr = async(row:attrData)=>{
   try {
    // 发请求删除属性
    await reqDeleteAttr(row.id)
    ElMessage({
        type:'success',
        message:`删除${row.attrName}成功`,
        duration:500,//约束提示信息的事件
    })
    // 再次发请求获取新的列表
    getAttrList()
   } catch (error) {
    ElMessage({
        type:'error',
        message:`删除${row.attrName}失败`
    })
   }
}

// 组件销毁
onUnmounted(()=>{
    categoryStore.c1Id = ''
    categoryStore.c2Id = ''
    categoryStore.c3Id = ''
    categoryStore.c1List = []
    categoryStore.c2List = []
    categoryStore.c3List = []
})
</script>

<style scoped>

</style>